/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package es.edn.pecera.client;

import es.edn.pecera.client.comms.DownloadManager;
import es.edn.pecera.client.comms.NotificationListener;
import es.edn.pecera.client.comms.ServerListener;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author jorge
 */
public class Pez implements NotificationListener {

    public static void main(String args[]) {
        Pez me = new Pez();
        try {
            me.live();
        } catch (Exception ex) {
            Logger.getLogger(Pez.class.getName()).log(Level.SEVERE, null, ex);
            return;
        }
    }
    String id;
    List<DownloadManager> downloads = new ArrayList<DownloadManager>();
    ServerListener serverListener;

    private Pez(){
        try {
            id = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException ex) {
            Logger.getLogger(Pez.class.getName()).log(Level.SEVERE, null, ex);
            throw new RuntimeException(ex);
        }
    }

    private void live() throws Exception {
        serverListener = new ServerListener();
        serverListener.setPort(6666);
        serverListener.setNotificationListener(this);
        serverListener.start();

        System.in.read();
        System.out.println("Cerrando sistema");
        serverListener.shutdown();
    }

    public void onUIDReceived(final String fromIP, final byte[] msg) {
        final DownloadManager dm = new DownloadManager();
        synchronized (this) {
            downloads.add(dm);
        }
        new Thread(new Runnable() {

            public void run() {
                Alimento ret = dm.download(new String(msg), id);
                synchronized (this) {
                    downloads.remove(dm);
                }
            }
        }).start();
    }

    public synchronized int getQueuedFilesCount() {
        return downloads.size();
    }
}
